package com.ray.export.runner.common;

import com.ray.export.empty.Empty;
import com.ray.export.exception.RunnerException;
import com.ray.export.runner.Hander;
import com.ray.export.runner.Runner;
import com.ray.export.runner.RunnerResult;
import com.ray.export.spring.ApplicationContextUtil;
import com.ray.export.strategy.data.DataModel;
import com.ray.export.strategy.result.Result;
import com.ray.export.strategy.result.SuccessResult;
import com.ray.export.template.ConfirmImportTemplate;
import com.ray.export.template.ExportTemplate;
import com.ray.export.template.ImportTemplate;
import com.ray.export.template.SyncImportTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.lang.annotation.Annotation;

/**
 * @author bo shen
 * @Description: 结果对象
 * @Class: ImportResultRunner
 * @Package com.ray.runner.imports
 * @date 2019/11/22 10:34
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class ResultRunner implements Runner<Annotation>, Hander {

    @Override
    public RunnerResult doRunner(Annotation annotation, DataModel dataModel, RunnerResult perResult) {
        try {
            if (annotation instanceof SyncImportTemplate) {
                return this.hander(((SyncImportTemplate) annotation).result(), dataModel, perResult);
            } else if (annotation instanceof ImportTemplate) {
                return this.hander(((ImportTemplate) annotation).result(), dataModel, perResult);
            } else if (annotation instanceof ConfirmImportTemplate) {
                return this.hander(((ConfirmImportTemplate) annotation).result(), dataModel, perResult);
            } else if (annotation instanceof ExportTemplate) {
                return this.hander(((ExportTemplate) annotation).result(), dataModel, perResult);
            }
            return this.hander(null, dataModel, perResult);
        } catch (Exception e) {
            //异常转换
            throw new RunnerException(e.getMessage(), Result.class);
        }
    }

    @Override
    public RunnerResult hander(Class<?> resultClass, DataModel dataModel, RunnerResult perResult) {
        log.info("执行结果处理对象");
        if (resultClass == Empty.class) {
            return new RunnerResult(Empty.class, dataModel,dataModel.getBeforeResult());
        }
        //判读配置是否符合规则
        if (!Result.class.isAssignableFrom(resultClass)) {
            log.error("结果处理配置错误");
            throw new RuntimeException("结果处理配置错误");
        }
        //获取执行对象
        Result result = (Result) ApplicationContextUtil.getApplicationContext().getBean(resultClass);
        if (ObjectUtils.isEmpty(result)) {
            log.error("获取执行对象异常[{}]", resultClass.getName());
            throw new RuntimeException("获取执行对象异常");
        }
        //获取结果
        SuccessResult r = result.doResult(dataModel);
        return new RunnerResult(Result.class, dataModel, r);
    }
}
